#!/bin/bash

# 函数：安装 Docker
install_docker() {
    if ! [ -x "$(command -v docker)" ]; then
        echo "Installing Docker..."
        sudo apt update
        sudo apt install -y docker.io
        sudo systemctl start docker
        sudo systemctl enable docker
    else
        echo "Docker is already installed."
    fi
}

# 函数：安装 Docker Compose
install_docker_compose() {
    if ! [ -x "$(command -v docker-compose)" ]; then
        echo "Installing Docker Compose..."
        sudo apt install -y docker-compose
    else
        echo "Docker Compose is already installed."
    fi
}

# 函数：克隆或更新 Dify 仓库
update_dify_repo() {
    local PROJECT_DIR="$HOME/dify"

    if [ -d "$PROJECT_DIR" ]; then
        echo "Updating Dify repository..."
        cd "$PROJECT_DIR" || exit
        git pull
    else
        echo "Cloning Dify repository..."
        git clone https://github.com/langgenius/dify.git "$PROJECT_DIR"
        cd "$PROJECT_DIR" || exit
    fi
}

# 函数：准备 .env 和 docker-compose.yaml 文件
prepare_config_files() {
    local DOCKER_DIR="$HOME/dify/docker"
    local COMPOSE_FILE="$DOCKER_DIR/docker-compose.yaml"

    cd "$DOCKER_DIR" || { echo "Failed to change directory to $PROJECT_DIR"; exit 1; }

    # 创建 .env 文件
    if [ ! -f ".env" ]; then
        if [ -f ".env.example" ]; then
            cp .env.example .env
        fi
    else
        echo ".env file already exists."
    fi

    # 创建 Docker Compose 文件
    if [ ! -f "docker-compose.yaml" ]; then
        echo "docker-compose.yaml file not exists. exit"
        exit 1
    fi
}

# 函数：启动或重启 Dify 服务
start_dify_services() {
    local DOCKER_DIR="$HOME/dify/docker"
    cd "$DOCKER_DIR" || { echo "Failed to change directory to $PROJECT_DIR"; exit 1; }

    echo "Starting Dify services..."
    docker compose down
    docker-compose up -d
    if [ $? -eq 0 ]; then
        echo "Dify has been successfully installed and started."
    else
        echo "Error: Failed to start Dify services." >&2
        exit 1
    fi
}

# 主程序
install_docker
install_docker_compose
update_dify_repo
prepare_config_files
start_dify_services

# 提示用户访问地址
# 获取当前网卡的 IP 地址（假设是 eth0 接口）
CURRENT_IP=$(hostname -I | awk '{print $1}')

# 检查是否成功获取到 IP 地址
if [ -z "$CURRENT_IP" ]; then
    echo "You can visit the Dify application at http://localhost/install"
else
    echo "You can visit the Dify application at http://$CURRENT_IP/install"
fi
